package com.github.baichuan.iot.protocol.utils;


import com.github.baichuan.iot.protocol.codec.MessageException;
import io.netty.buffer.ByteBuf;
import lombok.NonNull;

import java.time.LocalDateTime;

public class DateTimeCodec {
    public static byte[] encode(LocalDateTime dateTime) {
        int year = dateTime.getYear() - 2000;
        if(year < 0){
            throw new IllegalArgumentException("datetime must later than 2000-01-01");
        }

        byte[] bytes = new byte[6];
        bytes[0] = (byte)(year);
        bytes[1] = (byte)dateTime.getMonth().getValue();
        bytes[2] = (byte)dateTime.getDayOfMonth();
        bytes[3] = (byte)dateTime.getHour();
        bytes[4] = (byte)dateTime.getMinute();
        bytes[5] = (byte)dateTime.getSecond();
        return bytes;
    }

    public static LocalDateTime decode(@NonNull byte[] bytes) {
        if(bytes.length != 6){
            throw new IllegalArgumentException("bytes length must be 6");
        }

        int year = bytes[0] + 2000;
        int month = bytes[1];
        if(month < 1 || month > 12){
            new MessageException("month is illegal", bytes);
        }
        int day = bytes[2];
        if(day < 1 || day > 31){
            new MessageException("day is illegal", bytes);
        }
        int hour = bytes[3];
        if(day < 0 || day > 24){
            new MessageException("hour is illegal", bytes);
        }
        int minute = bytes[4];
        if(minute < 0 || day > 59){
            new MessageException("minute is illegal", bytes);
        }
        int second = bytes[5];
        if(second < 0 || second > 59){
            new MessageException("minute is illegal", bytes);
        }
        return LocalDateTime.of(year, month, day, hour, minute, second);
    }

    public static LocalDateTime decode(ByteBuf buf){
        byte[] bytes = new byte[6];
        buf.readBytes(bytes);
        return decode(bytes);
    }
}
